import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { message, Skeleton } from 'antd'
import style from './BoardStat.module.less'
import ReactEchartsCore from 'echarts-for-react/lib/core'
import * as echarts from 'echarts/core'
import { PieChart } from 'echarts/charts'
import { TitleComponent, LegendComponent, LegendScrollComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { strToNum } from '@src/assets/js/tool'
echarts.use([PieChart, LegendScrollComponent, TitleComponent, CanvasRenderer, LegendComponent])
class ArbitratorStatistic extends Component {
  state = {
    loading: false,
    colors: ['3b98ff', '29ba51', 'f9c514', 'ee3f59', '7d3fdc', '1f2c68', '2e2fc0', '14baba', 'F56B00', '009825', 'F0F2F5'],
    gender: [],
    genderLoading: false,
    educational: [],
    educationalLoading: false,
    occupation: [],
    occupationLoading: false
  }

  // 获取数据
  getData (group) {
    this.setState({ [`${group}Loading`]: true })
    this.$get('/api/xapc/board/statByFields', {
      fields: group
    })
      .then(res => {
        this.setState({ [`${group}Loading`]: false })
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        this.setState({
          [group]: res.data[group]
        })
      }).catch(() => this.setState({ [`${group}Loading`]: false }))
  }

  // 获取统计配置
  getOption (title, key) {
    let list = this.state[key]
    const map = {}
    let total = 0
    list.forEach(li => {
      total += strToNum(li.c)
    })
    list = list.map(li => {
      const obj = {
        name: li[key],
        value: strToNum(li.c),
        percent: total ? Math.round(strToNum(li.c) / total * 10000) / 100 + '%' : '0%'
      }
      map[li[key]] = obj
      return obj
    })
    return {
      tooltip: {
        trigger: 'item',
        formatter: (v) => {
          return `${v.name} ${v.value} (${(v.percent)}%)`
        }
      },
      legend: {
        orient: 'vertical',
        top: 40,
        left: '55%',
        icon: 'circle',
        itemGap: 4,
        itemWidth: 8,
        selectedMode: false,
        formatter: (name) => {
          const o = map[name]
          if (o) {
            return `{c|${o.name}} {b|${o.value}} {a|(${o.percent})}`
          }
        },
        textStyle: {
          rich: {
            a: {
              color: '#B7BBC8',
              lineHeight: 20
            },
            b: {
              color: '#7E889C',
              lineHeight: 20
            },
            c: {
              color: '#1F2229',
              lineHeight: 20
            }
          }
        }
      },
      series: [
        {
          name: title,
          type: 'pie',
          radius: ['50%', '68%'],
          center: ['30%', '50%'],
          height: 304,
          itemStyle: {
            borderWidth: 5,
            borderType: 'solid',
            borderColor: 'rgba(255, 255, 255, 1)'
          },
          label: {
            show: true,
            position: 'center',
            backgroundColor: '#fff',
            formatter: `{a|${title}}`,
            rich: {
              a: {
                color: '#1F2229',
                fontSize: 24
              }
            }
          },
          data: list.map((li, i) => {
            const d = {
              ...li,
              itemStyle: {
                color: `#${this.state.colors[i]}`
              }
            }
            return d
          })
        }
      ]
    }
  }

  // 前往查看详情
  toDetail (key, e) {
    this.props.addWindow({ id: 'BoardList', title: '委员会人员列表', componentName: 'BoardList', meta: { formData: { [key]: e.name } } })
  }

  componentDidMount () {
    this.getData('gender')
    this.getData('educational')
    this.getData('occupation')
  }

  // 渲染统计块
  renderItem (title, key, clickHandle = () => {}) {
    const option = this.getOption(title, key)
    const onEvents = {
      click: clickHandle
    }
    return (
      <div className={style.item}>
        <div className={style['item-inner']}>
          <div className={style['item-header']}>
            <span className={style['item-title']}>{title}</span>
          </div>
          <div className={style['item-body']}>
            {
              this.state[`${key}Loading`] ? (
                <div className={style.loading}><Skeleton active paragraph={{ rows: 6 }} /></div>
              ) : (
                <ReactEchartsCore style={{ width: '100%', height: '304px' }} echarts={echarts} onEvents={onEvents} option={option} />
              )
            }
          </div>
        </div>
      </div>
    )
  }

  render () {
    return (
      <div className={style.container}>
        <div className={style['title-line']}>
          <span>{this.props.title}</span>
        </div>
        <div className={style.list}>
          {this.renderItem('性别分布', 'gender', e => this.toDetail('gender', e))}
          {this.renderItem('学历分布', 'educational', e => this.toDetail('educational', e))}
        </div>
        <div className={style.list}>
          {this.renderItem('职业分类', 'occupation', e => this.toDetail('occupation', e))}
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
  }
})

export default connect(mapState, mapDispatch)(ArbitratorStatistic)
